//
//  UserInfoViewController.m
//  HWZB
//
//  Created by 许成雄 on 2017/4/24.
//  Copyright © 2017年 wonders. All rights reserved.
//

#import "UserInfoViewController.h"
#import "HWZBAPIRequest.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "UIImageView+Webcache.h"
#import "MBProgressHUD+Toast.h"
#import "NSString+Utils.h"
#import "RegexKit.h"
#import "Context.h"
#import "BankPickerView.h"


@interface UserInfoViewController () <BankPickerViewDelegate>

@property (strong, nonatomic) UIBarButtonItem *editButton;
@property (strong, nonatomic) UITextField *usernameTextField;
@property (strong, nonatomic) UITextField *idCardTextField;
@property (strong, nonatomic) UITextField *mobilePhoneTextField;
@property (strong, nonatomic) UITextField *bankCardTextField;
@property (strong, nonatomic) UITextField *bankTypeTextField;
@property (strong, nonatomic) UITextField *bankNameTextField;
@property (strong, nonatomic) BankPickerView *pickerView;
@property (strong, nonatomic) NSMutableArray *bankArray;
@property (strong, nonatomic) NSDictionary *bankDict;

@end

@implementation UserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = I_COLOR_BACKGROUND;
    [self setBackNavgationItem];
    self.navigationItem.title = @"个人信息";
    
    [self createUI];
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)pickerView:(BankPickerView *)pickerView didSelectAtBank:(NSDictionary *)bank {
    NSString *bankName = bank[@"bank"];
    NSString *bankTypeId = bank[@"bankId"];
    NSLog(@"%@", bankTypeId);
    self.bankTypeTextField.text = bankName;
}

#pragma mark - Private Method
- (void)bankTapAction {
    [self.view endEditing:NO];
    //显示银行选择框
    if(self.pickerView.hidden) {
        self.pickerView.hidden = NO;
    } else {
        self.pickerView.hidden = YES;
    }
    
}
- (void)editButtonAction {
    [self.view endEditing:NO];
    if(!self.pickerView.hidden) {
        self.pickerView.hidden = YES;
    }
    NSString *username = self.usernameTextField.text;
    NSString *idCard = self.idCardTextField.text;
    NSString *mobile = self.mobilePhoneTextField.text;
    NSString *bankCard = self.bankCardTextField.text;
    NSString *bankTypeName = self.bankTypeTextField.text;
    NSString *bankName = self.bankNameTextField.text;
    NSString *bankTypeId = [self getBankIdIndexByName:bankTypeName];
    
    //修改用户信息
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
    NSString *userId = [Context sharedInstance].loginID;
    [params setObject:userId forKey:@"id"];
    if(![NSString isBlankString:username]) {
        [params setObject:username forKey:@"name"];
    }
    if(![NSString isBlankString:idCard] && [RegexKit validateIDCardNumber:idCard]) {
        [params setObject:idCard forKey:@"idCard"];
    } else if(![NSString isBlankString:idCard] && [RegexKit validateIDCardNumber:idCard]) {
        [MBProgressHUD showToast:@"请输入正确的身份证号码" initWithView:self.view];
        return;
    }
    [params setObject:mobile forKey:@"mobile"];
    if(![NSString isBlankString:username]) {
        [params setObject:username forKey:@"name"];
    }
    if(![NSString isBlankString:bankCard]) {
        [params setObject:bankCard forKey:@"bankCard"];
    }
    if(![NSString isBlankString:bankName]) {
        [params setObject:bankTypeId forKey:@"bankTypeId"];
        [params setObject:bankName forKey:@"bankAddress"];
    }
    
    [SVProgressHUD showWithStatus:@"正在修改用户信息..." maskType:SVProgressHUDMaskTypeClear];
    [[HWZBAPIRequest sharedInstance] modifyUserInfoWithParams:params success:^(CommonInfo *resultInfo) {
        [SVProgressHUD dismiss];
        if(resultInfo) {
            [MBProgressHUD showToast:@"修改用户信息成功" initWithView:self.view];
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationUserInfoModify object:nil];
            [self performSelector:@selector(dismissThisViewController) withObject:nil afterDelay:1.5f];
        } else {
            [MBProgressHUD showToast:@"修改用户信息失败" initWithView:self.view];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
        [MBProgressHUD showToast:[error localizedDescription] initWithView:self.view];
    }];
}

- (void)dismissThisViewController {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)createUI {
    
    UIButton *editCustomView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 19 + 6, 22)];
    editCustomView.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [editCustomView setImage:[UIImage imageNamed:@"ic_me_edit"] forState:UIControlStateNormal];
    [editCustomView setImage:[UIImage imageNamed:@"ic_me_edit"] forState:UIControlStateFocused];
    [editCustomView setImage:[UIImage imageNamed:@"ic_me_edit"] forState:UIControlStateSelected];
    [editCustomView addTarget:self action:@selector(editButtonAction) forControlEvents:UIControlEventTouchUpInside];
    self.editButton = [[UIBarButtonItem alloc] initWithCustomView:editCustomView];
    self.navigationItem.rightBarButtonItem = self.editButton;

    
    UIView *sectionView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, TRANS_VALUE(40.0f) * 3 + 3.0f)];
    sectionView1.backgroundColor = I_COLOR_WHITE;
    [self createViewsInSectionView1:sectionView1];
    [self.view addSubview:sectionView1];
    
    
    UIView *sectionView2 = [[UIView alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(40.0f) * 3 + 3.0f + TRANS_VALUE(10.0f), SCREEN_WIDTH, TRANS_VALUE(40.0f) * 3 + 3.0f)];
    sectionView2.backgroundColor = I_COLOR_WHITE;
    [self createViewsInSectionView2:sectionView2];
    [self.view addSubview:sectionView2];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(40.0f) * 6 + 6.0f + TRANS_VALUE(10.0f), SCREEN_WIDTH, SCREEN_HEIGHT - 64.0f - (TRANS_VALUE(40.0f) * 6 + 6.0f + TRANS_VALUE(10.0f)))];
    headerView.backgroundColor = I_COLOR_WHITE;
    [self.view addSubview:headerView];
    
    self.pickerView = [[BankPickerView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 64.0f - 240.0f, SCREEN_WIDTH, 240.0f)];
    [self.view addSubview:self.pickerView];
    self.pickerView.delegate = self;
    self.pickerView.hidden = YES;
    
}

- (void)createViewsInSectionView1:(UIView *)sectionView1 {
    UILabel *usernameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, TRANS_VALUE(80.0f), TRANS_VALUE(40.0f))];
    usernameLabel.font = [UIFont systemFontOfSize:TRANS_VALUE(13.0f)];
    usernameLabel.textColor = I_COLOR_BLACK;
    usernameLabel.textAlignment = NSTextAlignmentRight;
    usernameLabel.text = @"真实姓名:";
    [sectionView1 addSubview:usernameLabel];
    
    self.usernameTextField = [[UITextField alloc] initWithFrame:CGRectMake(TRANS_VALUE(90.0f), TRANS_VALUE(0.0f), TRANS_VALUE(220.0f), TRANS_VALUE(40.0f))];
    self.usernameTextField.textAlignment = NSTextAlignmentLeft;
    self.usernameTextField.backgroundColor = I_COLOR_WHITE;
    self.usernameTextField.font = [UIFont systemFontOfSize:TRANS_VALUE(13.0f)];
    self.usernameTextField.borderStyle = UITextBorderStyleNone;
    self.usernameTextField.textColor = I_COLOR_BLACK;
    self.usernameTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入真实姓名" attributes:@{NSForegroundColorAttributeName:I_COLOR_GRAY}];
    self.usernameTextField.tintColor = I_COLOR_BLACK;
    [sectionView1 addSubview:self.usernameTextField];
    
    UIView *dividerView1 = [[UIView alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(40.0f), SCREEN_WIDTH, 1.0f)];
    dividerView1.backgroundColor = I_DIVIDER_COLOR;
    [sectionView1 addSubview:dividerView1];
    
    UILabel *idCardLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(40.0f) + 1.0f, TRANS_VALUE(80.0f), TRANS_VALUE(40.0f))];
    idCardLabel.font = [UIFont systemFontOfSize:TRANS_VALUE(13.0f)];
    idCardLabel.textColor = I_COLOR_BLACK;
    idCardLabel.textAlignment = NSTextAlignmentRight;
    idCardLabel.text = @"身份证号:";
    [sectionView1 addSubview:idCardLabel];
    
    self.idCardTextField = [[UITextField alloc] initWithFrame:CGRectMake(TRANS_VALUE(90.0f), TRANS_VALUE(40.0f) + 1.0f, TRANS_VALUE(220.0f), TRANS_VALUE(40.0f))];
    self.idCardTextField.textAlignment = NSTextAlignmentLeft;
    self.idCardTextField.backgroundColor = I_COLOR_WHITE;
    self.idCardTextField.borderStyle = UITextBorderStyleNone;
    self.idCardTextField.textColor = I_COLOR_BLACK;
    self.idCardTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入身份证号" attributes:@{NSForegroundColorAttributeName:I_COLOR_GRAY}];
    self.idCardTextField.tintColor = I_COLOR_BLACK;
    self.idCardTextField.font = [UIFont systemFontOfSize:TRANS_VALUE(13.0f)];
    [sectionView1 addSubview:self.idCardTextField];
    
    UIView *dividerView2 = [[UIView alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(40.0f) * 2 + 1.0f, SCREEN_WIDTH, 1.0f)];
    dividerView2.backgroundColor = I_DIVIDER_COLOR;
    [sectionView1 addSubview:dividerView2];
    
    UILabel *mobilePhoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(40.0f) * 2 + 2.0f, TRANS_VALUE(80.0f), TRANS_VALUE(40.0f))];
    mobilePhoneLabel.font = [UIFont systemFontOfSize:TRANS_VALUE(13.0f)];
    mobilePhoneLabel.textColor = I_COLOR_BLACK;
    mobilePhoneLabel.textAlignment = NSTextAlignmentRight;
    mobilePhoneLabel.text = @"手机号码:";
    [sectionView1 addSubview:mobilePhoneLabel];
    
    self.mobilePhoneTextField = [[UITextField alloc] initWithFrame:CGRectMake(TRANS_VALUE(90.0f), TRANS_VALUE(40.0f) * 2 + 2.0f, TRANS_VALUE(220.0f), TRANS_VALUE(40.0f))];
    self.mobilePhoneTextField.textAlignment = NSTextAlignmentLeft;
    self.mobilePhoneTextField.backgroundColor = I_COLOR_WHITE;
    self.mobilePhoneTextField.borderStyle = UITextBorderStyleNone;
    self.mobilePhoneTextField.textColor = I_COLOR_BLACK;
    self.mobilePhoneTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号码" attributes:@{NSForegroundColorAttributeName:I_COLOR_GRAY}];
    self.mobilePhoneTextField.tintColor = I_COLOR_BLACK;
    self.mobilePhoneTextField.font = [UIFont systemFontOfSize:TRANS_VALUE(13.0f)];
    [sectionView1 addSubview:self.mobilePhoneTextField];
    [self.mobilePhoneTextField setEnabled:NO];
    self.mobilePhoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    
    UIView *dividerView3 = [[UIView alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(44.0f) * 3 + 2.0f, SCREEN_WIDTH, 1.0f)];
    dividerView3.backgroundColor = I_DIVIDER_COLOR;
    [sectionView1 addSubview:dividerView3];
}

- (void)createViewsInSectionView2:(UIView *)sectionView2 {
    UILabel *bankCardLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, TRANS_VALUE(80.0f), TRANS_VALUE(40.0f))];
    bankCardLabel.font = [UIFont systemFontOfSize:TRANS_VALUE(13.0f)];
    bankCardLabel.textColor = I_COLOR_BLACK;
    bankCardLabel.textAlignment = NSTextAlignmentRight;
    bankCardLabel.text = @"银行卡号:";
    [sectionView2 addSubview:bankCardLabel];
    
    self.bankCardTextField = [[UITextField alloc] initWithFrame:CGRectMake(TRANS_VALUE(90.0f), TRANS_VALUE(0.0f), TRANS_VALUE(220.0f), TRANS_VALUE(40.0f))];
    self.bankCardTextField.textAlignment = NSTextAlignmentLeft;
    self.bankCardTextField.backgroundColor = I_COLOR_WHITE;
    self.bankCardTextField.borderStyle = UITextBorderStyleNone;
    self.bankCardTextField.textColor = I_COLOR_BLACK;
    self.bankCardTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入银行卡号" attributes:@{NSForegroundColorAttributeName:I_COLOR_GRAY}];
    self.bankCardTextField.tintColor = I_COLOR_BLACK;
    self.bankCardTextField.font = [UIFont systemFontOfSize:TRANS_VALUE(13.0f)];
    [sectionView2 addSubview:self.bankCardTextField];
    self.bankCardTextField.keyboardType = UIKeyboardTypeNumberPad;
    
    UIView *dividerView1 = [[UIView alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(40.0f), SCREEN_WIDTH, 1.0f)];
    dividerView1.backgroundColor = I_DIVIDER_COLOR;
    [sectionView2 addSubview:dividerView1];
    
    UILabel *bankTypeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(40.0f) + 1.0f, TRANS_VALUE(80.0f), TRANS_VALUE(40.0f))];
    bankTypeLabel.font = [UIFont systemFontOfSize:TRANS_VALUE(13.0f)];
    bankTypeLabel.textColor = I_COLOR_BLACK;
    bankTypeLabel.textAlignment = NSTextAlignmentRight;
    bankTypeLabel.text = @"所属银行:";
    [sectionView2 addSubview:bankTypeLabel];
    
    self.bankTypeTextField = [[UITextField alloc] initWithFrame:CGRectMake(TRANS_VALUE(90.0f), TRANS_VALUE(40.0f) + 1.0f, TRANS_VALUE(210.0f), TRANS_VALUE(40.0f))];
    self.bankTypeTextField.textAlignment = NSTextAlignmentLeft;
    self.bankTypeTextField.backgroundColor = I_COLOR_WHITE;
    self.bankTypeTextField.borderStyle = UITextBorderStyleNone;
    self.bankTypeTextField.textColor = I_COLOR_BLACK;
    self.bankTypeTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入所属银行" attributes:@{NSForegroundColorAttributeName:I_COLOR_GRAY}];
    self.bankTypeTextField.tintColor = I_COLOR_BLACK;
    self.bankTypeTextField.font = [UIFont systemFontOfSize:TRANS_VALUE(13.0f)];
    [sectionView2 addSubview:self.bankTypeTextField];
    self.bankTypeTextField.enabled = NO;
    
    UIImageView *arrowImageView = [[UIImageView alloc] initWithFrame:CGRectMake(TRANS_VALUE(308.0f), TRANS_VALUE(40.0f) + 1.0f + TRANS_VALUE(15.0f), TRANS_VALUE(6.0f), TRANS_VALUE(10.0f))];
    arrowImageView.contentMode = UIViewContentModeScaleAspectFit;
    [sectionView2 addSubview:arrowImageView];
    arrowImageView.image = [UIImage imageNamed:@"ic_me_arrow_black"];
    sectionView2.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapAction  = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bankTapAction)];
    [sectionView2 addGestureRecognizer:tapAction];
    
    
    UIView *dividerView2 = [[UIView alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(40.0f) * 2 + 1.0f, SCREEN_WIDTH, 1.0f)];
    dividerView2.backgroundColor = I_DIVIDER_COLOR;
    [sectionView2 addSubview:dividerView2];
    
    UILabel *bankNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(40.0f) * 2 + 2.0f, TRANS_VALUE(80.0f), TRANS_VALUE(40.0f))];
    bankNameLabel.font = [UIFont systemFontOfSize:TRANS_VALUE(13.0f)];
    bankNameLabel.textColor = I_COLOR_BLACK;
    bankNameLabel.textAlignment = NSTextAlignmentRight;
    bankNameLabel.text = @"开户银行:";
    [sectionView2 addSubview:bankNameLabel];
    
    self.bankNameTextField = [[UITextField alloc] initWithFrame:CGRectMake(TRANS_VALUE(90.0f), TRANS_VALUE(40.0f) * 2 + 2.0f, TRANS_VALUE(220.0f), TRANS_VALUE(40.0f))];
    self.bankNameTextField.textAlignment = NSTextAlignmentLeft;
    self.bankNameTextField.backgroundColor = I_COLOR_WHITE;
    self.bankNameTextField.borderStyle = UITextBorderStyleNone;
    self.bankNameTextField.textColor = I_COLOR_BLACK;
    self.bankNameTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入开户银行" attributes:@{NSForegroundColorAttributeName:I_COLOR_GRAY}];
    self.bankNameTextField.tintColor = I_COLOR_BLACK;
    self.bankNameTextField.font = [UIFont systemFontOfSize:TRANS_VALUE(13.0f)];
    [sectionView2 addSubview:self.bankNameTextField];
    
    UIView *dividerView3 = [[UIView alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(40.0f) * 3 + 2.0f, SCREEN_WIDTH, 1.0f)];
    dividerView3.backgroundColor = I_DIVIDER_COLOR;
    [sectionView2 addSubview:dividerView3];
}

- (void)loadData {
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
    NSString *userId = [Context sharedInstance].loginID;
    [params setObject:userId forKey:@"id"];
    [SVProgressHUD showWithStatus:@"正在获取用户信息..." maskType:SVProgressHUDMaskTypeClear];
    [[HWZBAPIRequest sharedInstance] getUserInfoWithParams:params success:^(UserInfo *userInfo) {
        [SVProgressHUD dismiss];
        if(userInfo) {
            [self showUserInfo:userInfo];
        } else {
            [self showUserInfo:nil];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
        [self showUserInfo:nil];
    }];
}

- (void)showUserInfo:(UserInfo *)userInfo {
    if(userInfo) {
        NSString *usernameStr = userInfo.name != nil ? userInfo.name : @"";
        self.usernameTextField.text = usernameStr;
        NSString *idCardStr = userInfo.idCard != nil ? userInfo.idCard : @"";
        self.idCardTextField.text = idCardStr;
        NSString *mobileStr = userInfo.mobile != nil ? userInfo.mobile : @"";
        self.mobilePhoneTextField.text = mobileStr;
        NSString *bankCardStr = userInfo.bankCard != nil ? userInfo.bankCard : @"";
        self.bankCardTextField.text = bankCardStr;
        NSString *bankTypeId = userInfo.bankTypeId != nil ? userInfo.bankTypeId : @"";
        self.bankTypeTextField.text = [self getBankNameById:bankTypeId];
        NSString *bankNameStr = userInfo.bankAddress != nil ? userInfo.bankAddress : @"";
        self.bankNameTextField.text = bankNameStr;
    } else {
        self.usernameTextField.text = @"";
        self.idCardTextField.text = @"";
        self.mobilePhoneTextField.text = @"";
        self.bankCardTextField.text = @"";
        self.bankTypeTextField.text = @"";
        self.bankNameTextField.text = @"";
    }
}

//根据银行ID获取银行名称
- (NSString *)getBankNameById:(NSString *)bankId {
    NSString *bankName = nil;
    for(NSDictionary *dict in [Context sharedInstance].bankArray) {
        if([dict[@"bankId"] isEqualToString:bankId]) {
            bankName = dict[@"bank"];
            break;
        }
    }
    return bankName;
}

//根据银行名称获取银行ID
- (NSString *)getBankIdIndexByName:(NSString *)bankName {
    NSString *indexStr = nil;
    for(int i = 0, n = (int)[Context sharedInstance].bankArray.count; i < n; i++) {
        NSDictionary *bankDict = [[Context sharedInstance].bankArray objectAtIndex:i];
        if([bankDict[@"bank"] isEqualToString:bankName]) {
            indexStr = [bankDict objectForKey:@"bankId"];
            break;
        }
    }
    return indexStr;
}

@end
